<template>
  <view class="interlude-container bg-main" v-if="visible">
    <!-- 最终结果转盘 - 动画完成后显示 -->
    <view class="final-result" v-if="animationCompleted">
      <image src="/static/images/turntable2.png" class="final-outer"></image>
      <image src="/static/images/turntable3.png" class="final-inner rotating2"></image>
    </view>

    <!-- 初始动画元素 - 动画完成前显示 -->
    <view v-else>
      <view class="user-info-container">
        <text class="name-display">{{ `${userInfo.userName}(${userInfo.gender})` }}</text>
        <text class="info-value">{{ userInfo.birthText }}</text>
      </view>

      <!-- 中心圆形命盘区域 -->
      <view class="destiny-chart-container">
        <view class="destiny-chart">
          <!-- 圆形文字环绕展示 -->
          <view class="chart-circle">
            <image :src="cornerItems[currentTab].imageUrl" class="turntable-bg rotating"></image>
            <view class="chart-center">
              <view class="chart-center-name">{{ userInfo.userName }}
                <view class="chart-center--time">{{ userInfo[cornerItems[currentTab].type] }} {{
                  cornerItems[currentTab].label.substring(0, 1) }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="corner-images">
          <view v-for="(corner, index) in cornerItems" :key="'corner-' + index" class="corner-item"
            :class="corner.position">
            <view v-show="currentTab === index" class="corner-image rhombus">八字<br>{{ corner.label }}</view>
            <image v-show="currentTab !== index" :src="corner.imageUrl" class="corner-image"></image>
            <text class="corner-label">{{ corner.label }}</text>
          </view>
        </view>
      </view>
      <!-- 底部进度区域 -->
      <view class="box-content ">
        <view class="feature-section ">
          <view class="tabs-container">
            <view class="tabs-row">
              <view v-for="(tab, index) in tabItems" :key="index" class="tab"
                :class="{ 'active': currentTab === index }" @tap="changeCurrentTab(index)">
                {{ tab.name }}
                <view class="tab-underline" :class="{ 'active': currentTab === index }"></view>
              </view>
            </view>
            <view class="tab-content">
              <view class="progress-item" v-for="(item, index) in getCurrentTabItems()" :key="'item-' + index">
                <view class="progress-text"> <span class="red-dot"></span> {{ item }}</view>
                <view v-show="tabsCompleted[index]" class="check">√</view>
                <u-loading-icon v-show="!tabsCompleted[index]" mode="circle" color="#b0b0b0" size="20"></u-loading-icon>
              </view>
            </view>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>

<script>
import { getMarryInfo, getUserInfo } from '@/api/fortune';
import { trackPageView } from '@/utils/track';
import { mapActions, mapGetters } from 'vuex';
import pageData from './data.js';

export default {
  name: 'InterludeComponent',
  props: {
    visible: {
      type: Boolean,
      default: true
    },
  },
  computed: {
    ...mapGetters('fortune', ['userInfo']),
    ...mapGetters('system', ['userCount'])
  },
  data() {
    return {
      pageData,
      cornerItems: pageData.cornerItems,
      tabItems: pageData.tabItems,
      currentTab: 0,
      tabsCompleted: [false, false, false],
      animationCompleted: false,
      timer: null,
      isLoading: false,
    };
  },
  mounted() {
    this.startAnimation();
  },
  methods: {
    ...mapActions('fortune', [
      'setUserInfo',
      'setOtherUserInfo',
      'setMarriageInfo',
    ]),
    // 开始动画和计算过程
    async startAnimation() {
      const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
      let currentIndex = 0;

      // 清理可能存在的旧定时器
      if (this.timer) {
        clearInterval(this.timer);
      }

      // 重置动画完成状态
      this.animationCompleted = false;

      // 设置 tab 切换定时器
      this.timer = setInterval(async () => {
        // 增加 tab 索引
        currentIndex++;

        if (currentIndex >= this.tabItems.length) {
          clearInterval(this.timer);
          this.animationCompleted = true;
          await sleep(1300);
          this.$emit('animation-complete');
          // 动画完成后跳转到支付页面
          this.initData();
          uni.navigateTo({
            url: '/pages/pay/index'
          });
          return;
        }

        // 重置当前 tab 的完成状态
        this.$set(this, 'tabsCompleted', [false, false, false]);
        this.currentTab = currentIndex;

        // 内部定时器：每秒完成一个 item
        const completeItems = async () => {
          for (let i = 0; i < this.tabsCompleted.length; i++) {
            await sleep(600);
            const newTabsCompleted = [...this.tabsCompleted];
            newTabsCompleted[i] = true;
            this.$set(this, 'tabsCompleted', newTabsCompleted);
          }
        };
        completeItems();
      }, 2300);

      // 立即开始第一个 tab 的动画
      this.$set(this, 'tabsCompleted', [false, false, false]);
      this.currentTab = currentIndex;
      const completeItems = async () => {
        for (let i = 0; i < this.tabsCompleted.length; i++) {
          await sleep(800);
          const newTabsCompleted = [...this.tabsCompleted];
          newTabsCompleted[i] = true;
          this.$set(this, 'tabsCompleted', newTabsCompleted);
        }
      };
      completeItems();
    },
    // 初始化数据
    async initData() {
      try {
        const [resUser, marryInfo] = await Promise.all([
          getUserInfo(),
          getMarryInfo(),
        ]);

        this.setUserInfo(resUser.data.basicInfo);
        this.setOtherUserInfo(resUser.data);
        this.setMarriageInfo(marryInfo.data);

      } catch (error) {
        console.error('获取数据失败:', error);
        this.$show.showToast('数据加载失败，请稍后再试');
      }
    },

    // 切换婚姻透视tab
    changeCurrentTab(index) {
      this.currentTab = index;
    },



    // 重置组件状态
    reset() {
      this.currentTab = 0;
      this.tabsCompleted = [false, false, false];
      this.animationCompleted = false;

      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
    getCurrentTabItems() {
      if (this.currentTab < 0 || this.currentTab >= this.tabItems.length) {
        return [];
      }
      return this.tabItems[this.currentTab].items;
    },

  },
  watch: {
    visible(newVal) {
      if (newVal) {
        // 当组件变为可见时，重置并开始动画
        this.reset();
      }
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  },
};
</script>

<style lang="scss" scoped>
/* 对现有的interlude-container应用背景 */
@import './interlude.scss';
</style>